package com.insight.entity;

import com.insight.common.enums.CollectionType;
import com.insight.common.enums.TaskStatus;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

/**
 * T042: 采集任务实体类
 * 记录元数据采集任务的执行状态和进度
 *
 * @author Insight Team
 */
@Entity
@Table(name = "collection_task",
        indexes = {
                @Index(name = "idx_collection_task_datasource", columnList = "datasource_id"),
                @Index(name = "idx_collection_task_status", columnList = "status"),
                @Index(name = "idx_collection_task_type", columnList = "collection_type"),
                @Index(name = "idx_collection_task_created_at", columnList = "created_at")
        })
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CollectionTask {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 关联的数据源
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "datasource_id", nullable = false)
    private DataSource dataSource;

    /**
     * 采集类型（全量/增量）
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "collection_type", nullable = false, length = 50)
    private CollectionType collectionType;

    /**
     * 任务状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "status", nullable = false, length = 50)
    private TaskStatus status;

    /**
     * 任务开始时间
     */
    @Column(name = "start_time")
    private LocalDateTime startTime;

    /**
     * 任务结束时间
     */
    @Column(name = "end_time")
    private LocalDateTime endTime;

    /**
     * 总表数量
     */
    @Column(name = "tables_total")
    private Integer tablesTotal;

    /**
     * 已采集表数量
     */
    @Column(name = "tables_collected")
    private Integer tablesCollected;

    /**
     * 失败表详情 (JSON格式存储)
     * 格式: [{"tableName": "...", "schemaName": "...", "errorMessage": "...", "retryCount": 0}]
     */
    @Column(name = "failed_tables", columnDefinition = "JSONB")
    private String failedTables;

    /**
     * 错误信息
     */
    @Column(name = "error_message", columnDefinition = "TEXT")
    private String errorMessage;

    /**
     * 创建时间
     */
    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @UpdateTimestamp
    @Column(name = "updated_at", nullable = false)
    private LocalDateTime updatedAt;

    /**
     * 生命周期回调：持久化之前
     */
    @PrePersist
    public void prePersist() {
        if (this.status == null) {
            this.status = TaskStatus.PENDING;
        }
        if (this.tablesCollected == null) {
            this.tablesCollected = 0;
        }
        if (this.tablesTotal == null) {
            this.tablesTotal = 0;
        }
    }

    /**
     * 生命周期回调：更新之前
     */
    @PreUpdate
    public void preUpdate() {
        // 可以在这里添加更新前的业务逻辑
        // 例如：自动设置endTime当status变为终止状态时
        if (status != null && status.isCompleted() && endTime == null) {
            endTime = LocalDateTime.now();
        }
    }
}
